<?php
/**
 * Created by PhpStorm.
 * User: Aliaksei Lazerka
 * Date: 9/30/14
 * Time: 10:52 PM
 */

namespace parser;

if (!defined('NYMPH_ROOT')) {
  define('NYMPH_ROOT', dirname("../../../../" . __FILE__));
  require(NYMPH_ROOT . '/local/loader/kernel/classes/URLClassLoader.php');
}

/**
 * The PropertyParser class provides the main functional
 * for parsing .properties files
 */
abstract class PropertyParser extends SimpleParser
{

  /**
   * @var Property[] with properties
   */
  private $properties = array();

  /**
   * (PHP 5)<br/>
   * Trying to parse some object
   * @param string $object
   * @return array array with parsed object
   */
  function parse($object)
  {
    $fileArray = file($object);
    foreach ($fileArray as $fileLine) {
      $key = $this->getKey($fileLine);
      if ($key) {
        $property = new Property();
        $property->setKey($key);
        $property->setValue($this->getValue($fileLine));
        $this->properties[] = $property;
      }
    }
  }

  function __construct()
  {
    parent::__construct();
    $this->allowedExtensions = array("properties");
  }

  /**
   * (PHP 5)<br/>
   * Is used to get key from parsed string
   * @param string $string
   * @return string string key
   */
  function getKey($string)
  {
    if (strpos($string, '#') === 0) {
      return false;
    } else {
      $eqPos = strpos($string, '=');
      return trim(substr($string, 0, $eqPos - 1));
    }
  }

  /**
   * (PHP 5)<br/>
   * Is used to get value from parsed string
   * @param string $string
   * @return string string value
   */
  function getValue($string)
  {
    $eqPos = strpos($string, '=');
    return trim(substr($string, $eqPos + 1));
  }

  function getValueByKey($key)
  {
    $key = trim($key);
    foreach ($this->properties as $property) {
      if ($property->getKey() == $key) {
        return $property->getValue();
      }
    }
    return "prop:" . $key;
  }

  function parseAll()
  {
    parent::parseAll();
  }

}